package com.atguigu.gulimall.product.exception;

import com.atguigu.common.exception.BizCodeEnume;
import com.atguigu.common.exception.RRException;
import com.atguigu.common.utils.R;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.util.HashMap;
import java.util.Map;

/**
 * GuliMall的异常处理类
 *
 * @author wu on 2020/11/25 0025
 */
@RestControllerAdvice(basePackages = "com.atguigu.gulimall.product.controller")
public class GuliMallException {
    private static final Logger LOGGER = LoggerFactory.getLogger(GuliMallException.class);

    @ExceptionHandler(MethodArgumentNotValidException.class)  // 数据校验异常处理方法
    public R getErrorMess(MethodArgumentNotValidException e) {
        Map<String, String> errorHashMap = new HashMap<>();
        BindingResult bindingResult = e.getBindingResult();
        bindingResult.getFieldErrors().forEach(exceptions -> {
            String field = exceptions.getField();
            String defaultMessage = exceptions.getDefaultMessage();
            errorHashMap.put(field, defaultMessage);
        });
        LOGGER.error("异常信息是{},异常类型是{}", e.getMessage(), e.getClass());
        return R.error(BizCodeEnume.VAILD_EXCEPTOIN.getCode(), BizCodeEnume.VAILD_EXCEPTOIN.getMsg()).put("data", errorHashMap);
    }


    /*
        @ExceptionHandler(Throwable.class)  // 未知异常处理方法
        public R handlerException(Throwable throwable) {
            LOGGER.error("异常信息是{},异常类型是{}", throwable.getMessage(), throwable.getClass());
            return R.error(BizCodeEnume.UNKNOW_EXCEPTION.getCode(), BizCodeEnume.UNKNOW_EXCEPTION.getMsg());
        }
    */
/*    @ExceptionHandler(Exception.class)
    public R exception(Exception e) {
        LOGGER.error("Java抛出异常错误信息为{}，开发人员友好提示为{}", e, e.getMessage());
        return R.error(20002, e.getMessage());
    }*/

    @ExceptionHandler(RRException.class)
    public R rRException(RRException e) {
        LOGGER.error("错误编码为{}，错误信息为{},e.getStackTrace()[0]{}", e.getCode(), e.getMsg(), e.getStackTrace()[0]);
        return R.error(e.getCode(), e.getMsg());
    }
}
